package com.esandinfo.tyc.util;

import com.alibaba.fastjson.JSON;
import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.IOException;

/**
 * @author panda
 */
public class DingTalkRobotUtil {

    private static Logger logger = LoggerFactory.getLogger(DingTalkRobotUtil.class);

    private static final String ROBOT_WEBHOOK = "https://oapi.dingtalk.com/robot/send?access_token=0c9601e7a26bbb3215d94fc9ce1d150c32a4c5c3da81d0b8e1a0547a8217ba33";

    private static void dealDingDingMsgSend(String textMsg) {

        //获得当前客户端对象
        HttpClient httpClient = HttpClients.createDefault();
        //通过url获得一个请求对象
        HttpPost httpPost = new HttpPost(ROBOT_WEBHOOK);
        //添加请求头
        httpPost.addHeader("Content-Type", "application/json; charset=utf-8");
        //创建请求内容对象
        StringEntity stringEntity = new StringEntity(textMsg,"utf-8");
        httpPost.setEntity(stringEntity);

        try {
            //通过请求对象获取响应对象
            HttpResponse response = httpClient.execute(httpPost);
            //判断响应码是否为200
            if(response.getStatusLine().getStatusCode() == HttpStatus.SC_OK){

                String result = EntityUtils.toString(response.getEntity(),"utf-8");
                logger.info("[发送钉钉消息]响应结果: " + JSON.toJSONString(result));
            }
        } catch (IOException e) {
            logger.error("[发送钉钉消息]error: " + e.getMessage(),e);
        }

    }

    public void sendMsg2DingTalk(String type,String companyName,String url){
        String textMsg = "{\"msgtype\": \"link\", \"link\": {\"text\": \"" + type +": [" + companyName + "] \n (" + url + ")\", \"title\": \"" + type + "\", \"picUrl\": \"\", \"messageUrl\": \"" + url + "\"}}";
        dealDingDingMsgSend(textMsg);
    }

    public static void main(String[] args) {
        DingTalkRobotUtil dingTalkRobotUtil = new DingTalkRobotUtil();
        dingTalkRobotUtil.sendMsg2DingTalk("贷前报告","北京一砂信息技术有限公司","http://wiki.esandinfo.com/page/display?document_id=137%E2%80%9C");
    }


}
